import React from 'react';
import _ from 'underscore';

import {Scope} from 'lib/scopeFactory';
import TimeStore from 'lib/stores/time-store'

import {propConfig, coreApi, parseToTopbar} from '../apis/core-util';

export default class MainScope extends Scope {
  constructor(props, context) {
    super(props, context);

    this.viewKey = 'avg_resp_ajax';
    this.$state = {
      topbar:{
        loading:true
      },
      sortOptions:_.chain(propConfig)
                   .pick('avg_resp_ajax', 'count_resp_ajax', 'error_rate')
                   .map((value,key)=>({
                     key,
                     label:value.label
                   }))
                   .value()
    }; // $state

    this.topbarApi = coreApi({
      size:1,
      limit:20,
      classify:'domain',
      urlName:()=> this.viewKey === 'error_rate' ? 'ajax/ajaxerrordata' : 'ajax/ajaxdata',
      viewKey:()=>this.viewKey,
      order:()=>propConfig[this.viewKey].order
    },TimeStore.getValue);
  } // constructor

  $change_sort(payload){
    this.viewKey = payload.key;
    this.fetch()
  } // $change_sort

  fetch() {
    this.topbarApi
        .fetch()
        .progress(()=>{
          this.$state.topbar = {
            loading:true
          };
          this.emit();
        })
        .fail((error,params)=> this.$state.topbar = { error })
        .done((data,params)=>{
          this.$state.topbar = {
            data:parseToTopbar(data,params,{
              classifyTree:[
                {
                  key:'domain'
                }, {
                  key:'url',
                  requireId:'domainId'
                }
              ]
            })
          };
        })
        .always(()=> this.emit());
  } // fetch

  $settime(payload){
    this.fetch();
  } // $settime

  $load() {
    this.fetch();
  }
}
